import { useControlController, useNamespace } from '@ibiz-template/vue3-util';
import {
  defineComponent,
  nextTick,
  onBeforeUnmount,
  onMounted,
  PropType,
  ref,
  watch,
} from 'vue';
import { IDEChart } from '@ibiz/model-core';
import { init } from 'echarts';
import { createUUID } from 'qx-util';
import { ChartController, IControlProvider } from '@ibiz-template/runtime';
import './chart.scss';

const ChartControl = defineComponent({
  name: 'IBizChartControl',
  props: {
    modelData: { type: Object as PropType<IDEChart>, required: true },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    provider: { type: Object as PropType<IControlProvider> },
    mdctrlActiveMode: { type: Number, default: undefined },
    loadDefault: { type: Boolean, default: true },
  },
  setup() {
    const c = useControlController((...args) => new ChartController(...args));
    const ns = useNamespace(`control-${c.model.controlType!.toLowerCase()}`);
    const chartRef = ref();
    const maxHeight = ref(0); // 图表表格的高度,后续会根据表格位置进行计算
    const uuid = createUUID();

    // 设置表格的高
    const setHeight = async () => {
      await nextTick();
      const el = document.getElementById(uuid);
      if (el) {
        if (
          c.state.gridPosition === 'bottom' ||
          c.state.gridPosition === 'top'
        ) {
          maxHeight.value = el.offsetHeight / 2 - 8;
        } else {
          maxHeight.value = el.offsetHeight - 16;
        }
      }
    };

    // 获取表格的数据
    const getGridData = () => {
      return c.state.gridData || [];
    };

    onMounted(() => {
      const chart = init(chartRef.value);
      c.initChart(chart);
      window.addEventListener('resize', setHeight);
      setHeight();
    });

    // 表格显示时计算表格的高度
    watch(
      () => c.state.showGrid,
      () => {
        setHeight();
      },
      {
        immediate: true,
      },
    );

    // 绘制表格
    const renderGrid = () => {
      return (
        <el-table
          ref='tableRef'
          data={getGridData()}
          border
          style={{ width: '100%' }}
          max-height={maxHeight.value}
          header-row-class-name={ns.e('grid-header')}
        >
          {c.state.gridHeaders.map((column: IData) => {
            return (
              <el-table-column
                prop={column.id}
                align='center'
                label={column.name}
              ></el-table-column>
            );
          })}
        </el-table>
      );
    };

    onBeforeUnmount(() => {
      window.removeEventListener('resize', setHeight);
    });

    return {
      c,
      ns,
      chartRef,
      uuid,
      renderGrid,
    };
  },
  render() {
    return (
      <iBizControlBase controller={this.c}>
        <div id={this.uuid} class={this.ns.b('chart-container')}>
          <el-empty
            class={[
              this.ns.e('empty'),
              this.ns.is('no-data', this.c.state.items.length === 0),
            ]}
            description='暂无数据'
          />
          <div
            class={[
              this.ns.e('chart-grid'),
              this.ns.is('no-data', this.c.state.items.length === 0),
              this.ns.is('show-grid', this.c.state.showGrid),
              {
                [this.ns.em('chart-grid', this.c.state.gridPosition)]:
                  this.c.state.showGrid,
              },
            ]}
          >
            <div
              class={[
                this.ns.e('chart-grid-container'),
                this.ns.is(this.c.state.gridPosition, this.c.state.showGrid),
                this.ns.is('no-grid', !this.c.state.showGrid),
              ]}
            >
              <div ref='chartRef' class={[this.ns.e('chart')]}>
                {ibiz.i18n.t('control.chart.chartPlaceholder')}
              </div>
            </div>
            {this.c.state.showGrid ? (
              <div class={this.ns.e('grid')}>{this.renderGrid()}</div>
            ) : null}
          </div>
        </div>
      </iBizControlBase>
    );
  },
});

export default ChartControl;
